<?php

class CoursesController extends GxController {

    public function filters() {
        return array(
            'accessControl', // perform access control for CRUD operations
        );
    }

    public function accessRules() {
        return array(
            array('allow', // allow all users to perform 'index' and 'view' actions
                'actions' => array('viewcourse'),
                'users' => array('*'),
            ),
            array('allow', // allow authenticated user to perform 'create' and 'update' actions
                'actions' => array('create', 'setAuthKey', 'update', 'StarRatingAjax', 'managecourse'),
                'users' => array('@'),
            ),
            array('deny', // deny all users
                'users' => array('*'),
            ),
        );
    }

    public function actionviewCourse($id) {
        $this->layout = 'detailspage';
        $courseTag = '';
        $venueDetails = '';
        $discount = '';
        $priceRange = '';
        $classTrainerRate = '';
        $classtotalCountTrainerate = '';
        $model = $this->loadModel($id, 'Courses');
        $userId = getLoginUserId();
        if ($model->status == 1 OR $userId == $model->users_id) {
            $makeQueryModel = new MakeQuery;
            $timingMakequeryModel = new TimingMakequery;
            $booknow = 'Make Query';
            $discount = CourseEarlyDiscount::findMaxDscountByCourse($model->id);
            $priceRange = CourseBatche::findMinMaxPriceByCoursebatch($model->id);
            $funLearing = Courses::getfunlearing($model->id);
            $courseTag = ClassCourseTags::getClassCourseTag($model->course_tag);
            $userType = ($model->users_id == '') ? 'backend' : 'front-end';
            $classTrainerRate = Classes::trainerPossitiverate($userType, $model);
            $classtotalCountTrainerate = Classes::trainertotalRate($userType, $model);
            $userDetails = ($model->users_id == '') ? Users::getBackEndUser($model->backend_user_id) : Users::getFrontEndUser($model->users_id);
            $imagePath = ($model->users_id == '') ? 'backend/' . $model->backend_user_id : $model->users_id;
            /* --------------------find all venue name by classid start---------------------- */
            $venueData = CourseWithVenue::getVenueName($model->id);
            foreach ($venueData as $value => $name) {
                $venueDetails.= CHtml::tag('option', array('value' => $name->courseVenue->id), CHtml::encode($name->courseVenue->name), true);
            }
            /* --------------------find all venue name by classid end---------------------- */

            /* Check session of comapre class couese */
            if (Yii::app()->session['allcompare_ids'] <> "") {
                $compare_class_course_id = Yii::app()->session['allcompare_ids'];
                $checkIds = rtrim($compare_class_course_id, ',');
                $checkIds = explode(',', $checkIds);
                if (count($checkIds) > 0) {
                    $compareIds = $checkIds;
                }
            } else {
                $compareIds = array();
            }

            /* End Check session of comapre class couese */
            $this->render('_viewCourse', array(
                'model' => $model, 'booknow' => $booknow, 'classTag' => $courseTag, 'userDetails' => $userDetails, 'venueDetails' => $venueDetails, 'discount' => $discount,
                'priceRange' => $priceRange, 'imagePath' => $imagePath, 'funLearing' => $funLearing, 'userType' => $userType,
                'classTrainerRate' => $classTrainerRate, 'classtotalCountTrainerate' => $classtotalCountTrainerate, 'compareIds' => $compareIds, 'makeQueryModel' => $makeQueryModel, 'timingMakequeryModel' => $timingMakequeryModel,
            ));
        } else
            throw new CHttpException(400, Yii::t('app', Message::EXCEPTION_NOT_ACTIVATE_COURSE));
    }

    public function actionCreate() {
        $model = new Courses;
        $modelFunLearning = new FunLearning;
        Yii::app()->user->setState('authKey', NULL);
        $authKey = time() . guid();
        if (isset($_POST['Courses'])) {
            $model->setAttributes($_POST['Courses']);
            $model->setAttribute('course_type_id', COURSE_CLASS_TYPE);
            $model->setAttribute('create_time', SkillConfig::CreateDateTime());
            $model->setAttribute('status', SkillConfig::STATUS_DEACTIVE);
            $classtags = '';
            $classTagText = '';
            if (!empty($_POST['Courses']['course_tag'])) {
                foreach ($_POST['Courses']['course_tag'] as $key => $value) {
                    $classTag = ClassCourseTags::model()->findByPk($value);
                    $classTagText .=$classTag->tag_name . ',';
                    $classtags.=$value . ',';
                }
            }
            $valid = $model->validate();
            if ($valid) {
                $model->setAttributes($_REQUEST['Courses']);
                $model->setAttribute('course_tag_description', $classTagText);
                $model->setAttribute('users_id', getLoginUserId());
                $model->setAttribute('auth_key', $authKey);
                $model->setattribute('course_tag', $classtags);
                if ($model->save(false)) {
                    if (!empty($_POST['ClassCourseTags']['tag_name'])) {
                        $this->saveClassSuggestTag($_POST['ClassCourseTags']['tag_name']);
                    }
                    self::saveCoursesFunLearning($model);
                    self::saveCourseTargetAudience($model);
                    Yii::app()->user->setState('authKey', $model->auth_key);
                    $this->redirect(array('ClassVenue/Coursevenue'));
                }
            }
        }

        $this->render('create', array('model' => $model, 'modelFunLearning' => $modelFunLearning));
    }

    public function actionUpdate() {
        $authKey = Yii::app()->user->getState('authKey');
        $modelFunLearning = new FunLearning;
        if (!empty($authKey)) {
            $course = Courses::model()->findByAttributes(array('auth_key' => $authKey));
            $model = $this->loadModel($course->id, 'Courses');
            $FunLearning = $modelFunLearning->findByAttributes(array('courses_id' => $course->id));
            if (count($FunLearning) > 0) {
                $modelFunLearning = $FunLearning;
            }
            $model->setAttribute('update_time', SkillConfig::CreateDateTime());
            if (getLoginUserId() == $model->users_id) {
                if (isset($_POST['Courses'])) {
                    $model->setAttributes($_POST['Courses']);
                    $classtags = '';
                    $classTagText = '';
                    if (!empty($_POST['Courses']['course_tag'])) {
                        foreach ($_POST['Courses']['course_tag'] as $key => $value) {
                            $classTag = ClassCourseTags::model()->findByPk($value);
                            $classTagText .=$classTag->tag_name . ',';
                            $classtags.=$value . ',';
                        }
                    }
                    $model->setAttribute('course_type_id', COURSE_CLASS_TYPE);
                    $model->setattribute('course_tag', $classtags);
                    $model->setAttribute('course_tag_description', $classTagText);
                    if ($model->save()) {
                        if (!empty($_POST['ClassCourseTags']['tag_name'])) {
                            $this->saveClassSuggestTag($_POST['ClassCourseTags']['tag_name']);
                        }
                        self::saveCoursesFunLearning($model);
                        self::saveCourseTargetAudience($model);
                        Yii::app()->user->setState('authKey', $model->auth_key);
                        $this->redirect(array('ClassVenue/Coursevenue'));
                    }
                }
                $this->render('update', array('model' => $model, 'modelFunLearning' => $modelFunLearning));
            }
        } else {
            throw new CHttpException(400, Yii::t('app', 'Your request is invalid.'));
        }
    }

    protected function saveClassSuggestTag($suggestTagVal) {
        $classCoursetag = new ClassCourseTags();
        $classCoursetag->setAttribute('tag_name', $suggestTagVal);
        $classCoursetag->setAttribute('create_time', SkillConfig::CreateDateTime());
        $classCoursetag->setAttribute('status', SkillConfig::STATUS_DEACTIVE);
        $classCoursetag->setAttribute('users_id', getLoginUserId());
        $classCoursetag->save(false);
    }

    private static function saveCoursesFunLearning($model) {
        (!$model->isNewRecord) ? Courses::deleteClassFunLearning($model->id) : '';
        $modelFunLearning = new FunLearning;
        if (isset($_POST['FunLearningValue'])) {
            $fun = $_POST['FunLearningValue']['fun'];
            $learn = SkillConfig::FUN_LEARING_LIMIT - $fun;
            $modelFunLearning->setAttribute('fun', $fun);
            $modelFunLearning->setAttribute('learn', $learn);
            $modelFunLearning->setAttribute('courses_id', $model->id);
            $modelFunLearning->setAttribute('status', 1);
            $modelFunLearning->setAttribute('create_time', SkillConfig::CreateDateTime());
            $modelFunLearning->save(FALSE);
        }
    }

    private static function saveCourseTargetAudience($model) {
        (!$model->isNewRecord) ? Courses::deleteCoursesTargetAudience($model->id) : '';
        if (isset($_POST['Courses']['classesTargetAudiences']) && !empty($_POST['Courses']['classesTargetAudiences'])) {
            foreach ($_POST['Courses']['classesTargetAudiences'] as $targetAudience) {
                $modelClassTargetAudience = new ClassesTargetAudience();
                $modelClassTargetAudience->target_audience_id = $targetAudience;
                $modelClassTargetAudience->courses_id = $model->id;
                $modelClassTargetAudience->save(false);
            }
        }
    }

    public function actionStarRatingAjax() {
        $ratingAjax = isset($_POST['rate']) ? $_POST['rate'] : 0;
        echo $ratingAjax;
    }

    public function actionmanagecourse($location = '', $classType = '') {
        $this->layout = 'detailspage';
        $classVenueVals = ClassVenue::model()->findAll('users_id=' . getLoginUserId());
        $criteria = new CDbCriteria();
        $criteria->addCondition('users_id=' . getLoginUserId());
        if (!empty($classType) || !empty($location)) {
            $date = date('Y-m-d');
            $criteria->select = 't.*,B.date_from,p.courses_id,p.course_venue_id';
            $criteria->join = 'LEFT JOIN skill_course_with_venue p ON  (t.id = p.courses_id) LEFT JOIN skill_course_batche B ON (t.id = B.courses_id)';
            if (!empty($location)) {
                $criteria->addCondition('p.course_venue_id = "' . $location . '"');
            }
            if ($classType == 1) {
                $criteria->addCondition('B.date_from<="' . $date . '"');
                $criteria->addCondition('B.date_to>="' . $date . '"');
            }
            if ($classType == 2) {
                $criteria->addCondition('B.date_from>"' . $date . '"');
            } if ($classType == 3) {
                $criteria->addCondition('B.date_from<"' . $date . '"');
            }
            $criteria->group = 'B.courses_id';
        }
        $dataProvider = new CActiveDataProvider('Courses', array('criteria' => $criteria,
                    'pagination' => array(
                        'pageSize' => 5,
                    ),
                ));

        $this->render('managecourse', array(
            'dataProvider' => $dataProvider, 'classVenueVals' => $classVenueVals
        ));
    }

}
